package springboot.study.project.util.es;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.elasticsearch.client.transport.TransportClient;

/**
 * @ClassName: ElasticSearchPoolUtil
 * @Description: ElasticSearch连接池工具类
 * @Author: baoxia
 * @Date: 2020-07-05 13:21
 * @Version: 1.0
 **/
public class ElasticSearchPoolUtil {
    /**
     * 对象池配置类，不写也可以，采用默认配置
     */
    private static GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

    {
        // 采用默认配置maxTotal是8，池中有8个client
        poolConfig.setMaxTotal(8);
    }

    /**
     * 要池化的对象的工厂类，这个是我们要实现的类
     */
    private static EsClientPoolFactory esClientPoolFactory = new EsClientPoolFactory();
    /**
     * 利用对象工厂类和配置类生成对象池
     */
    private static GenericObjectPool<TransportClient> clientPool = new GenericObjectPool<>(esClientPoolFactory, poolConfig);


    /**
     * 获得一个ES客户端对象
     *
     * @return ES客户端对象
     * @throws Exception 异常
     */
    public static TransportClient getClient() throws Exception {
        // 从池中取一个对象
        TransportClient client = clientPool.borrowObject();
        return client;
    }

    /**
     * 归还对象
     *
     * @param client
     */
    public static void returnClient(TransportClient client) {
        // 使用完毕之后，归还对象
        clientPool.returnObject(client);
    }

}
